package com.yougou.utils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yougou.data.model.Goods;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class FavoriteManager {
    
    private static final String KEY_FAVORITES_PREFIX = "key_favorites_";
    private static List<Goods> favorites;
    private static Gson gson = new Gson();
    
    
    private static String getFavoritesKey() {
        String uid = UserManager.isLogin() ? UserManager.getCurrentUser().getUid() : "guest";
        return KEY_FAVORITES_PREFIX + uid;
    }
    
    
    public static void addFavorite(Goods goods) {
        List<Goods> favoriteList = getFavorites();
        
        // 检查是否已存在
        for (Goods item : favoriteList) {
            if (item.getGoodsId() == goods.getGoodsId()) {
                return; // 已经收藏过了
            }
        }
        
        favoriteList.add(0, goods); // 添加到列表开头
        saveFavorites(favoriteList);
    }
    
    
    public static void removeFavorite(int goodsId) {
        List<Goods> favoriteList = getFavorites();
        favoriteList.removeIf(goods -> goods.getGoodsId() == goodsId);
        saveFavorites(favoriteList);
    }
    
    
    public static boolean isFavorite(int goodsId) {
        List<Goods> favoriteList = getFavorites();
        for (Goods item : favoriteList) {
            if (item.getGoodsId() == goodsId) {
                return true;
            }
        }
        return false;
    }
    
    
    public static List<Goods> getFavorites() {
        // 每次都重新加载，确保数据是当前用户的
        String json = SPUtils.getString(getFavoritesKey());
        if (json.isEmpty()) {
            favorites = new ArrayList<>();
        } else {
            Type type = new TypeToken<List<Goods>>() {}.getType();
            favorites = gson.fromJson(json, type);
            if (favorites == null) {
                favorites = new ArrayList<>();
            }
        }
        return favorites;
    }
    
    
    public static int getFavoriteCount() {
        return getFavorites().size();
    }
    
    
    public static void clearFavorites() {
        favorites = new ArrayList<>();
        saveFavorites(favorites);
    }
    
    
    private static void saveFavorites(List<Goods> favoriteList) {
        favorites = favoriteList;
        String json = gson.toJson(favoriteList);
        SPUtils.putString(getFavoritesKey(), json);
    }
}

